package com.example.indenture.config;


import com.example.indenture.common.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * 增强型返回,利用aop思想进行统一数据返回(用于处理忘记调用common包下AjaxResult中的方法;
 *
 * @author CY
 * @date 2023/03/13 22:17
 **/
@ControllerAdvice
@ResponseBody
public class ResponseAdvice implements ResponseBodyAdvice {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 这里true为进行统一处理,false为不进行统一处理
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    /**
     * 对数据格式进行效验和封装
     *
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //如果做了统一处理,直接通过
        if (body instanceof Result) {
            return body;
        }
        //没有通过,处理数据
        if (body instanceof String) {
            return objectMapper.writeValueAsString(Result.ok(body));
        }
        return Result.ok(body);
    }
}
